from . import models
from django.core.exceptions import ObjectDoesNotExist


def get_stock_data(is_end_or_not):
    """
    获取关注股票信息，并返回
    :param is_end_or_not: 查询正在关注还是已结束关注股票，true表示正在关注
    :return:
    """
    if is_end_or_not == "False":
        is_end = False
    elif (is_end_or_not == "True"):
        is_end = True

    if is_end:
        all_data = models.attention_stock.objects.filter(is_end=is_end).order_by(
            "start_attention_date")  # 关注股票按关注早->晚排序
    else:
        all_data = models.attention_stock.objects.filter(is_end=is_end).order_by(
            "-end_attention_data")  # 关注股票按取消关注晚->排序
    """
    需要将models转换成json特定格式，才能被bootstrap table插件读取。
    另一种为json对象格式，必须要有total和rows两个key，
    {"total": 2,"rows": [{"id": 0,"name": "Item 0","price": "$0"},{"id": 1,"name": "Item 1","price": "$1"}]}，
    且键的名字必须与下方columns的field值一样，才能读取到数据,但是如果后台
    没有处理的话，前台会在第一页显示全部数据，为client时，前台会提示：没有找到匹配的记录。
    """
    total = all_data.count()
    rows = []
    result = {"total": total, "rows": rows}
    for data in all_data:
        if is_end:  # 如果时关注股票，则查找目前最新价格
            newest = models.daily.objects.filter(ts_code=data.ts_code).order_by("-trade_date")[0]
            end_data = newest.trade_date
            end_price = newest.close
        else:  # 如果是不再关注股票
            end_data = data.end_attention_data
            end_price = data.end_attention_price
        pct_chg = round((end_price - data.start_attention_price) * 100 / data.start_attention_price, 2)

        rows.append({'ts_code': data.ts_code, 'start_attention_date': data.start_attention_date, 'name': data.name,
                     'start_attention_price': data.start_attention_price, 'end_attention_date': end_data,
                     'end_attention_price': end_price, 'is_end': data.is_end, 'pct_chg': pct_chg})

    return result


def update_attention_state(ts_code_list, is_end):
    # 修改为取消关注
    if not (is_end):
        for code in ts_code_list:
            newest = models.daily.objects.filter(ts_code=code).order_by("-trade_date")[0]
            models.attention_stock.objects.filter(ts_code=code).update(is_end=is_end,
                                                                       end_attention_data=newest.trade_date,
                                                                       end_attention_price=newest.close)
    # 重新关注,则重新在数据库中插入新的关注数据
    if is_end:
        #####如股票仍在关注列表中，则不关注
        attention_stock_in_db = models.attention_stock.objects.filter(is_end=1)  # 查找数据库中仍处于关注状态的股票信息
        in_db_ts_code_list = []
        for attention_in_db in attention_stock_in_db:
            in_db_ts_code_list.append(attention_in_db.ts_code)
        ts_code_list = list(set(ts_code_list) - set(in_db_ts_code_list))  # 求差集
        #####
        attention_stock_list = []
        for ts_code in ts_code_list:
            newest = models.daily.objects.filter(ts_code=ts_code).order_by("-trade_date")[0]
            attention_stock_tmp = models.attention_stock()
            attention_stock_tmp.ts_code = ts_code
            try:
                attention_stock_tmp.name = models.stock_basic.objects.get(ts_code=ts_code).name
            except ObjectDoesNotExist:
                attention_stock_tmp.name = ''
            attention_stock_tmp.start_attention_date = newest.trade_date
            day_close = newest.close
            attention_stock_tmp.start_attention_price = day_close
            attention_stock_tmp.is_end = True
            attention_stock_list.append(attention_stock_tmp)
        models.attention_stock.objects.bulk_create(attention_stock_list)
    return


def clear_attention_date(is_end):
    """
    删除相关数据
    :param is_end:
    :return:
    """
    if is_end == '0':
        is_end = False
    else:
        is_end = True
    models.attention_stock.objects.filter(is_end=is_end).delete()
